#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
独立结果窗口模块
提供一个可以独立显示数据、图表和查询信息的窗口
"""

import logging
from typing import Dict, List, Any, Optional

from PySide6.QtCore import Qt, QSize, Signal, Slot, QSettings
from PySide6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QTabWidget,
                              QToolBar, QToolButton, QMenu,
                              QMessageBox, QStatusBar)
from PySide6.QtGui import QIcon, QCloseEvent, QAction

from ui.results_view import ResultsView
from core.query_manager import QueryResult


# 初始化日志记录器
logger = logging.getLogger("detached_results")


class DetachedResultsWindow(QMainWindow):
    """独立的结果窗口类，用于展示数据、图表和查询信息"""
    
    # 信号定义
    window_closed = Signal(str)  # 窗口ID
    
    def __init__(self, window_id: str, title: str = "查询结果", parent=None):
        """初始化独立结果窗口
        
        Args:
            window_id: 窗口唯一标识
            title: 窗口标题
            parent: 父窗口
        """
        super().__init__(parent)
        self.window_id = window_id
        self.setWindowTitle(title)
        self.resize(800, 600)
        
        # 初始化UI
        self._init_ui()
        
        # 加载窗口状态
        self._load_window_state()
    
    def _init_ui(self):
        """初始化UI"""
        # 设置中央部件
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        
        # 主布局
        self.main_layout = QVBoxLayout(self.central_widget)
        self.main_layout.setContentsMargins(0, 0, 0, 0)
        
        # 创建工具栏
        self._create_toolbar()
        
        # 创建标签页
        self.tab_widget = QTabWidget()
        self.tab_widget.setTabsClosable(True)
        self.tab_widget.tabCloseRequested.connect(self._close_tab)
        self.main_layout.addWidget(self.tab_widget)
        
        # 创建状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.status_bar.showMessage("就绪")
    
    def _create_toolbar(self):
        """创建工具栏"""
        toolbar = QToolBar("结果工具栏")
        toolbar.setMovable(False)
        toolbar.setIconSize(QSize(16, 16))
        self.addToolBar(toolbar)
        
        # 导出按钮
        export_action = QAction("导出数据", self)
        export_action.setStatusTip("导出当前数据到文件")
        export_action.triggered.connect(self._export_current_data)
        toolbar.addAction(export_action)
        
        # 复制按钮
        copy_action = QAction("复制数据", self)
        copy_action.setStatusTip("复制选中的数据")
        copy_action.triggered.connect(self._copy_current_selection)
        toolbar.addAction(copy_action)
        
        toolbar.addSeparator()
        
        # 刷新按钮
        refresh_action = QAction("刷新", self)
        refresh_action.setStatusTip("刷新当前结果")
        refresh_action.triggered.connect(self._refresh_current_view)
        toolbar.addAction(refresh_action)
    
    def add_result_tab(self, title: str, query_id: str = None) -> ResultsView:
        """添加一个新的结果标签页
        
        Args:
            title: 标签页标题
            query_id: 查询ID
            
        Returns:
            结果视图组件
        """
        # 创建结果视图
        results_view = ResultsView()
        results_view.query_id = query_id
        
        # 添加到标签页
        tab_index = self.tab_widget.addTab(results_view, title)
        self.tab_widget.setCurrentIndex(tab_index)
        
        return results_view
    
    def display_result(self, df, query_sql=None, execution_time=None, tab_title: str = "查询结果"):
        """显示查询结果
        
        Args:
            df: 数据表
            query_sql: 查询SQL
            execution_time: 执行时间
            tab_title: 标签页标题
        """
        # 检查是否已有相同标题的标签页
        for i in range(self.tab_widget.count()):
            if self.tab_widget.tabText(i) == tab_title:
                # 已存在，切换到该标签页
                self.tab_widget.setCurrentIndex(i)
                results_view = self.tab_widget.widget(i)
                results_view.display_result(df, query_sql, execution_time)
                return results_view
        
        # 不存在，创建新标签页
        results_view = self.add_result_tab(tab_title)
        results_view.display_result(df, query_sql, execution_time)
        
        return results_view
    
    def _close_tab(self, index: int):
        """关闭标签页
        
        Args:
            index: 标签页索引
        """
        # 获取结果视图
        results_view = self.tab_widget.widget(index)
        
        # 清理资源
        if hasattr(results_view, 'cleanup'):
            results_view.cleanup()
        
        # 移除标签页
        self.tab_widget.removeTab(index)
        
        # 如果没有剩余标签页，关闭窗口
        if self.tab_widget.count() == 0:
            self.close()
    
    def _export_current_data(self):
        """导出当前数据"""
        current_view = self.tab_widget.currentWidget()
        if isinstance(current_view, ResultsView):
            current_view._show_export_dialog()
    
    def _copy_current_selection(self):
        """复制当前选择的数据"""
        current_view = self.tab_widget.currentWidget()
        if isinstance(current_view, ResultsView):
            current_view._copy_selection()
    
    def _refresh_current_view(self):
        """刷新当前视图"""
        current_view = self.tab_widget.currentWidget()
        if isinstance(current_view, ResultsView):
            current_view._refresh_view()
    
    def _load_window_state(self):
        """加载窗口状态"""
        settings = QSettings()
        settings.beginGroup(f"DetachedResultsWindow_{self.window_id}")
        
        # 加载窗口几何
        geometry = settings.value("geometry")
        if geometry:
            self.restoreGeometry(geometry)
        
        settings.endGroup()
    
    def _save_window_state(self):
        """保存窗口状态"""
        settings = QSettings()
        settings.beginGroup(f"DetachedResultsWindow_{self.window_id}")
        
        # 保存窗口几何
        settings.setValue("geometry", self.saveGeometry())
        
        settings.endGroup()
    
    def closeEvent(self, event: QCloseEvent):
        """窗口关闭事件
        
        Args:
            event: 关闭事件
        """
        # 保存窗口状态
        self._save_window_state()
        
        # 清理所有标签页
        for i in range(self.tab_widget.count()):
            results_view = self.tab_widget.widget(i)
            if hasattr(results_view, 'cleanup'):
                results_view.cleanup()
        
        # 发送窗口关闭信号
        self.window_closed.emit(self.window_id)
        
        # 处理事件
        event.accept() 